package com.rongke.web.ud;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongke.web.ud.constant.CompareImgItem;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.rongke.web.ud.constant.EnumCompareImgFileSource.SESSION_ID;
import static com.rongke.web.ud.constant.EnumCompareImgFileSource.URL;
import static com.rongke.web.ud.constant.EnumCompareImgFileType.GRID_PHOTO;
import static com.rongke.web.ud.constant.EnumCompareImgFileType.LIVING_PHOTO;


/**
 * 云慧眼API接口调用-测试用例
 *
 * @author geosmart
 * @date 2017-06-12
 */
public class UDAPI {
    //TODO 线上地址见对接文档中的服务描述，商户公钥，商户密钥商户开户时会下发到商户对接人员邮件
    //商户公钥
    static final String pub_key = "d61bb374-56ae-453c-bf98-3e9431b7a61f";
    //商户密钥
    static final String security_key = "1e2b5f52-30ca-4901-a8a8-08876bd320b2";

    //身份证正面OCR接口
    static final String IDCARD_FRONT_OCR = "https://idsafe-auth.udcredit.com/front/4.3/api/idcard_front_photo_ocr/pub_key/" + pub_key;
    //身份证背面OCR接口
    static final String IDCARD_BACK_OCR = "https://idsafe-auth.udcredit.com/front/4.3/api/idcard_back_photo_ocr/pub_key/" + pub_key;
    //OCR识别更新接口
    static final String UPDATE_OCR_INFO = "https://idsafe-auth.udcredit.com/front/4.3/api/update_ocr_info/pub_key/" + pub_key;

    //实名验证接口
    static final String IDCARD_VERIFY = "https://idsafe-auth.udcredit.com/front/4.3/api/idcard_verify/pub_key/" + pub_key;
    //人脸比对接口
    static final String FACE_COMPARE = "https://idsafe-auth.udcredit.com/front/4.3/api/face_compare/pub_key/" + pub_key;

    //活体检测接口
    static final String LVING_DETECTION = "http://10.1.30.51:8000/idsafe-front/front/4.3/api/living_detection/pub_key/" + pub_key;
    //活体检测唇语验证码接口
    static final String VALIDATEDATA = "http://10.1.30.51:8000/idsafe-front/front/4.3/api/get_living_validate_data/pub_key/" + pub_key;

    static final String CHASET_UTF_8 = "UTF-8";

    /**
     * 生成md5签名
     */
    public static String getMD5Sign(String pub_key, String partner_order_id, String sign_time, String security_key) throws UnsupportedEncodingException {
        String signStr = String.format("pub_key=%s|partner_order_id=%s|sign_time=%s|security_key=%s", pub_key, partner_order_id, sign_time, security_key);
        System.out.println("测试输入签名signField：" + signStr);
        return MD5Utils.MD5Encrpytion(signStr.getBytes("UTF-8"));
    }

    /**
     * 格式化日期字符串 yyyyMMddHHmmss
     */
    public static String getStringDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }


//    @Before
//    public void setup() throws IOException {
//        System.out.println("setup...");
//    }

    /**
     * 生成请求header
     */
    public static JSONObject getRequestHeader(String session_id) throws IOException {
        JSONObject header = new JSONObject();
        if (session_id != null && !session_id.equals("")) {
            header.put("session_id", session_id);
        }
        String sign_time = getStringDate(new Date());
        String partner_order_id = UUID.randomUUID().toString();
        String sign = getMD5Sign(pub_key, partner_order_id, sign_time, security_key);
        header.put("partner_order_id", partner_order_id);
        header.put("sign", sign);
        header.put("sign_time", sign_time);
        return header;
    }

    /**
     * Http请求
     */
    public static JSONObject doHttpRequest(String url, JSONObject reqJson) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        //设置传入参数
        StringEntity entity = new StringEntity(reqJson.toJSONString(), CHASET_UTF_8);
        entity.setContentEncoding(CHASET_UTF_8);
        entity.setContentType("application/json");
        System.out.println(url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        HttpResponse resp = client.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            String respContent = EntityUtils.toString(he, CHASET_UTF_8);
            return (JSONObject) JSONObject.parse(respContent);
        }
        return null;
    }

    /**
     * 实名验证接口
     */
    public static JSONObject idCardVerify(String id_number, String id_name) throws IOException {
        JSONObject reqJson = new JSONObject();
        reqJson.put("header", getRequestHeader(""));

        JSONObject body = new JSONObject();
        body.put("id_number", id_number);
        body.put("id_name", id_name);
        body.put("verify_type", "1");
        reqJson.put("body", body);

        System.out.println("实名验证接口-输入参数：" + JSON.toJSONString(reqJson, true));
        JSONObject resp_front = doHttpRequest(IDCARD_VERIFY, reqJson);
        System.out.println("实名验证接口-输出结果：" + JSON.toJSONString(resp_front, true));
        return resp_front;
    }


    /**
     * 人脸比对接口
     */

    public static JSONObject faceCompare(String session_id,String facePhoto) throws IOException {
        JSONObject reqJson = new JSONObject();
        reqJson.put("header", getRequestHeader(null));

        JSONObject body = new JSONObject();
        reqJson.put("body", body);

        //photo1参数
        CompareImgItem comparePhoto1 = new CompareImgItem(URL, LIVING_PHOTO, facePhoto);
        body.put("photo1", comparePhoto1);

        //photo2参数
        CompareImgItem comparePhoto2 = new CompareImgItem(SESSION_ID, GRID_PHOTO, session_id);
        body.put("photo2", comparePhoto2);


        System.out.println("人脸比对接口-输入参数：" + JSON.toJSONString(reqJson, true));
        JSONObject resp_front = doHttpRequest(FACE_COMPARE, reqJson);
        System.out.println("人脸比对接口-输出结果：" + JSON.toJSONString(resp_front, true));
        return resp_front;
    }


//    @After
//    public void teardown() throws IOException {
//        System.out.println("teardown...");
//    }

}
